package com.smartwrite.service;

import com.smartwrite.dto.ReportGenerationRequest;
import com.smartwrite.dto.TaskResponse;
import com.smartwrite.entity.TaskInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

/**
 * 报告生成服务
 * 负责处理报告生成的业务逻辑
 */
@Service
public class ReportGenerationService {

    @Autowired
    private TaskStorageService taskStorageService;

    @Autowired
    private ReportExecutorService reportExecutorService;

    /**
     * 生成报告
     *
     * @param request 报告生成请求
     * @return 任务响应
     */
    public TaskResponse generateReport(ReportGenerationRequest request) {
        // 生成唯一任务ID
        String taskId = "report-" + UUID.randomUUID().toString();

        // 创建任务信息
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setTaskId(taskId);
        taskInfo.setStatus("started");
        taskInfo.setPrompt(request.getPrompt());
        taskInfo.setModel(request.getModel());
        taskInfo.setEnableSearch(request.getEnableSearch());
        taskInfo.setSearchEngine(request.getSearchEngine());
        taskInfo.setApiKeys(request.getApiKeys());
        taskInfo.setStartTime(Instant.now());

        // 存储任务信息
        taskStorageService.storeTask(taskInfo);

        // 异步执行报告生成
        CompletableFuture.runAsync(() -> {
            reportExecutorService.executeReportGeneration(taskInfo);
        });

        return new TaskResponse(taskId, "started", "报告生成任务已启动");
    }
}